package com.iot.system.core.impl;

import com.iot.common.utils.DateUtils;
import com.iot.system.core.CoreDeviceParametersService;
import com.iot.system.domain.DeviceParameterRecord;
import com.iot.system.service.IDeviceParameterRecordService;
import com.iot.system.service.IDeviceStateService;
import com.iot.system.vo.DeviceTodayParametersVo;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class CoreDeviceParametersServiceImpl implements CoreDeviceParametersService {

    @Resource
    private IDeviceParameterRecordService iDeviceParameterRecordService;
    @Resource
    private IDeviceStateService iDeviceStateService;

    public DeviceTodayParametersVo getDeviceTodayParameters(Date date, Long deviceId) {
        //判断时间是否今天 如果不是今天则不需要判断是否开机
        if (!DateUtils.isSameDay(date,new Date())){
            return null;
        }
        //判断设备是否停机 如果设备停机则根据停机的时间点获取数据 如果未停机则根据当前时间获取数据
        DeviceTodayParametersVo parametersVo = new DeviceTodayParametersVo();
        //处理当前时间 根据当前时间获取当前时间向前推移6个整十的时间点
        List<Date> dateList = DateUtils.getDateListByTimesTamp(date,6);

        //根据dateList 的第一个和最后一个时间点查询数据库
        List<DeviceParameterRecord>  deviceParameterRecordList = iDeviceParameterRecordService.getDeviceParameterRecordListByDate(dateList.get(0),dateList.get(5),deviceId);
        if(CollectionUtils.isEmpty(deviceParameterRecordList)){
            return parametersVo;
        }

        if (CollectionUtils.isEmpty(dateList)){
            return parametersVo;
        }

        ///转map
        Map<String, Date> dateMap = dateList.stream().collect(Collectors.toMap(item -> DateUtils.getDateYearMonthDayByDate(item), item -> item));

        //转map
        Map<String, List<DeviceParameterRecord>> collect = deviceParameterRecordList.stream().collect(Collectors.groupingBy(item -> DateUtils.getDateYearMonthDayByDate(item.getCreateTime())));

        //根据时间获取参数数据
        dateMap.forEach((key, value) -> {
            DeviceTodayParametersVo.DataItem dataItem = new DeviceTodayParametersVo.DataItem();
            if (collect.containsKey(key)) {
                List<DeviceParameterRecord> deviceParameterRecords = collect.get(key);
                DeviceParameterRecord record = deviceParameterRecords.get(0);
                dataItem.setCreate_data(DateUtils.getYearMonthDayByDate(value));
                dataItem.setCreate_time(DateUtils.getHourMinuteByDate(value));
                dataItem.setParameters_value(record.getParametersValue());
            }
            parametersVo.getData().add(dataItem);
        });

        return parametersVo;
    }
}
